<template>
  <el-main>
    <div class="w-full flex flex-row gap-2 border-b-gray-300 border p-2">
      <el-input v-model="searchQuery" placeholder="动物名称" class="max-w-[200px]"></el-input>
        <el-select  v-model="FilterType" placeholder="种类" style="width: 200px" v-if="USER.role==='3'||USER.role==='4'" >
          <el-option
              v-for="item in TypeOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      <div>
        <el-button type="success" @click="FilterfeedRecord">查询</el-button>
        <el-button type="danger" @click="FilterReset">重置</el-button>
      </div>
    </div>
    <el-table :data="feedlist" style="width: 100%">
        <el-table-column prop="feed.id" label="编号"  />
        <el-table-column prop="animal.name" label="名称" />
        <el-table-column prop="animal.type" label="类别"  />
        <el-table-column prop="animal.age" label="年龄" />
        <el-table-column prop="animal.gender" label="性别" />
        <el-table-column prop="animal.healthStatus" label="当前状态" >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.animal.healthStatus === '1'">健康</el-tag>
            <el-tag type="warning" v-if="scope.row.animal.healthStatus === '2'">受伤</el-tag>
            <el-tag type="danger" v-if="scope.row.animal.healthStatus === '3'">肥胖</el-tag>
            <el-tag type="danger" v-if="scope.row.animal.healthStatus === '4'">生病</el-tag>
          </template>
        </el-table-column>
        <el-table-column  prop="animal.nowWeight" label="当前体重/kg" />
        <el-table-column prop="keepername" label="饲养员" />
        <el-table-column prop="feed.foodName" label="食物名称" />
        <el-table-column prop="feed.foodWeigh" label="食物重量/kg" />
        <el-table-column fixed="right" label="操作">
        <template #default="scope" >
          <div class="flex flex-row gap-1 w-[200px]">
              <el-button v-if="scope.row.animal.endTime" type="info" disabled @click="">已封档</el-button>
            <button   v-if="!scope.row.animal.endTime" class="bg-element-green text-white px-2.5 py-1 rounded-md hover:bg-element-hover-green" @click="HandleEdit(scope.row)">编辑</button>

            <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="你确认要删除吗？"
                @confirm="Remove(scope.row)"
                >
              <template #reference>
                <button   v-if="!scope.row.animal.endTime"  class="bg-red-500 text-white px-2.5 py-1 rounded-md hover:bg-red-600">删除</button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>

    </el-table>

    <!-- 编辑窗口-->
    <el-dialog v-model="isFlag.dialogVisbaleFeed"  title="编辑界面" width="500" center>
      <el-form >
        <el-form-item label="食物名称:" label-width="80px">
          <el-input v-model="currentFeed.foodName" ></el-input>
        </el-form-item>
        <el-form-item label="食物重量:" label-width="80px">
          <el-input v-model="currentFeed.foodWeigh" ><template #append>千克（Kg）</template></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isFlag.dialogVisbaleFeed = false">取消</el-button>
          <el-button type="primary" @click="SaveEdit" >确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>
<script setup lang="ts">
import {reactive,ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {InfoFilled} from "@element-plus/icons-vue";
const CurrentFeed=ref();
const filteredList=ref([])
let currentFeed=reactive({
  foodName:String,
  foodWeigh:String,
});
const isFlag = reactive({
  dialogVisbaleFeed:false,
})
const feedlist = ref([])
const searchQuery = ref();
const FilterType =ref();
const USER=JSON.parse(localStorage.getItem('user'));
const TypeOptions = ref({})
function init(){
  console.log(USER.id)
  axios.get('http://localhost:8080/feed/getlist/byuserid?id='+USER.id)
      .then(request =>{
        feedlist.value = request.data
          console.log(request.data)
      })
  axios.get('http://localhost:8080/animal/gettype')
      .then(request =>{
        console.log(request.data)
        TypeOptions.value=request.data;
        console.log(TypeOptions)
      })
}
init();
function FilterfeedRecord (){
  axios.get('http://localhost:8080/feed/getlist')
      .then(request =>{
        console.log(request.data)
        filteredList.value = request.data
        if(FilterType.value!=null){
          filteredList.value=filteredList.value.filter(item =>item.animal.type && item.animal.type == FilterType.value)
          console.log(FilterType.value)
        }

        if(searchQuery.value!=null){
          filteredList.value=filteredList.value.filter(item => {
            return item.animal.name.includes(searchQuery.value);
          });}
        feedlist.value=filteredList.value;
      })
}
function HandleEdit(currentfeed){
  CurrentFeed.value=null;
  CurrentFeed.value=currentfeed;
  console.log(CurrentFeed.value.feed.foodName)
  currentFeed.foodName=CurrentFeed.value.feed.foodName;
  currentFeed.foodWeigh=CurrentFeed.value.feed.foodWeigh;
  isFlag.dialogVisbaleFeed=true;
}
// 检查字符串是否包含特殊字符的函数
function checkSpecialCharacters(input: string): boolean {
    // 此处可以根据需要定义特殊字符的规则，例如只允许中英文和数字，不允许特殊符号等
    const pattern = /[!@#$%^&*()+\=\[\]{};':"\\|,.<>\/?~]/;
    return pattern.test(input);
}

// 显示错误信息的弹窗
function showErrorMessage(message: string) {
    ElMessageBox.alert(message, '提示', {
        confirmButtonText: '确定',
    });
}
// 表单验证函数，确保主题不为空且不包含特殊字符
function validateFormFeed(tmpAnimal): boolean {
    if (tmpAnimal.foodName.trim() === '') {
        showErrorMessage('食物名称不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.foodName)) {
        showErrorMessage('食物名称不能包含特殊字符');
        return false;
    }
    if (tmpAnimal.foodWeigh.trim() === '') {
        showErrorMessage('食物重量不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.foodWeigh)) {
        showErrorMessage('食物重量不能包含特殊字符');
        return false;
    }

    return true;
}



function SaveEdit(){
    // 检查表单是否通过验证
    if (!validateFormFeed(currentFeed)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
  CurrentFeed.value.feed.foodName=currentFeed.foodName;
  CurrentFeed.value.feed.foodWeigh=currentFeed.foodWeigh;
  axios.post('http://localhost:8080/feed/update',CurrentFeed.value.feed)
      .then(request =>{
        console.log(request.data)
        if (request.data){
          ElMessage({
            message:'修改成功',
            type:'success'
          })
          isFlag.dialogVisbaleFeed=false;
          init();
        }
      })

}
function Remove(currentFeed){
  console.log(currentFeed)
  axios.post('http://localhost:8080/feed/remove',currentFeed.feed)
      .then(request =>{
        if (request.data){
          ElMessage({
            message:'删除成功',
            type:'success'
          })
          location.reload()
        }
      })
}
function FilterReset(){
  location.reload();
}

</script>